<?php

declare(strict_types=1);

namespace NanQi\Hope\Factory;

use Hyperf\Contract\ContainerInterface;
use Hyperf\Di\Container;
use Hyperf\Di\Definition\DefinitionSourceFactory;
use Hyperf\Di\Exception\Exception;
use Hyperf\Utils\ApplicationContext;
use NanQi\Hope\App;


class AppFactory
{
    /**
     * Create an application with a chosen preset.
     * @return App
     */
    public static function createApp(): App
    {
        // Setting ini and flags
        self::prepareFlags();

        // Prepare container
        $container = self::prepareContainer();

        $app = new App($container);
        $container->set(App::class, $app);
        return $app;
    }

    protected static function prepareContainer(): ContainerInterface
    {
        $container = new Container((new DefinitionSourceFactory(true))());
//        $container->define(BoundInterface::class, ContainerProxy::class);

        ApplicationContext::setContainer($container);
        return $container;
    }

    protected static function prepareFlags(int $hookFlags = SWOOLE_HOOK_ALL)
    {
        ini_set('display_errors', 'on');
        ini_set('display_startup_errors', 'on');
        error_reporting(E_ALL);
        $reflection = new \ReflectionClass(\Composer\Autoload\ClassLoader::class);
        $projectRootPath = dirname($reflection->getFileName(), 3);
        ! defined('BASE_PATH') && define('BASE_PATH', $projectRootPath);
        ! defined('SWOOLE_HOOK_FLAGS') && define('SWOOLE_HOOK_FLAGS', $hookFlags);


        \Hyperf\Di\ClassLoader::init();
    }
}
